#include <cstdio>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include"mutex/Mutex.hpp"

// struct data
// {
//     std::string name;
//     pthread_mutex_t *lockp;
// };

Mutex lock;

int ticket=1000;
// pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;

void* route(void*args)
{
    // data*d=static_cast<data*>(args);
    std::string name=static_cast<const char*>(args);
    while(true)
    {
        // lock.Lock();
        GuardMutex mutex(&lock);
        if(ticket>0)
        {
            usleep(10000);
            printf("%s 抢到票号：%d\n",name.c_str(),ticket--);
            // lock.Unlock();
        }
        else
        {
            // lock.Unlock();
            break;
        }
    }
    return (void*)0;
}


int main()
{
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock, nullptr);

    pthread_t t1, t2, t3, t4;
    // data d1 = {"thread-1", &lock};
    pthread_create(&t1, nullptr, route, (void*)"thread-1");

    // data d2 = {"thread-2", &lock};
    pthread_create(&t2, nullptr, route, (void*)"thread-2");

    // data d3 = {"thread-3", &lock};
    pthread_create(&t3, nullptr, route, (void*)"thread-3");

    // data d4 = {"thread-4", &lock};
    pthread_create(&t4, nullptr, route, (void*)"thread-4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    // pthread_mutex_destroy(&lock);

    return 0;
}